package com.ryan.demo.resource.utils;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.util.StringUtils;

public class ResourceHelper {
    public static final String CAT_SMOOKS = "smooks";
    
    private static Map<String, String> categoryDirMap = new HashMap<String,String>();
    private static String classpath;
    
    static{
        initClassPath();
    }
    
    public ResourceHelper() {
        
    }
    public static String getFilePath(String category, String fileName){
        String dir = categoryDirMap.get(category);
        
        return dir+fileName;
    }
    
    public static String getClassPath(){
        return classpath;
    }
    
    public void addCategoryDir(String cat, String dir){
        categoryDirMap.put(cat, getPath(dir));
    }
    
    public void setCategoryDirMap(Map<String, String> categoryDirs) {
        ResourceHelper.categoryDirMap.clear();
        for(Entry<String,String> e : categoryDirs.entrySet()){
            this.addCategoryDir(e.getKey(), e.getValue());
        }
    }
    
    private static void initClassPath(){
        ClassLoader  loader  =  Thread.currentThread().getContextClassLoader();  
        URL  url  =  loader.getResource(".");
        classpath = url.getPath();
    }
    
    public static String getPath(String pathDef){
        String path= pathDef;
        if(StringUtils.hasText(pathDef)){
            if(pathDef.startsWith("classpath:")){
                path = classpath+pathDef.replaceFirst("classpath:", "").trim();
            }
        }
        return path;
    }
}
